package my.jwds.p110;

import my.jwds.p94.TreeNode;

public class IsBalanced {

    public static void main(String[] args) {
        IsBalanced obj = new IsBalanced();
        Integer [] nums = {1,2,2};
        TreeNode root = TreeNode.to_binaryHaveNull(nums);
        System.out.println(obj.isBalanced(root));
    }


    public boolean isBalanced(TreeNode root) {
        return dfs(root) != -1;
    }


    public int dfs(TreeNode root){
        if (root == null)return 0;
        int left = dfs(root.left);
        int right = dfs(root.right);
        if (left == -1 || right == -1 || Math.abs(right - left) > 1)return -1;
        int max = Integer.max(left,right);
        return max+1;
    }

}